package com.srd.phone.bean;

import android.content.Intent;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.srd.phone.activity.BaseActivity;
import com.srd.phone.activity.DialogUpdateActivity;
import com.srd.phone.application.HttpStringRequest;

import org.json.JSONObject;

import java.io.Serializable;

public class UpdateVersionInfo implements Serializable {

    /**
     *
     */
    private static final long serialVersionUID = 1L;

    public int versionCode; //版本号
    public String url;
    public String changelog; //更新内容
    public String md5;

    public static UpdateVersionInfo parser(String json) {
        UpdateVersionInfo info = new UpdateVersionInfo();
        try {
            JSONObject jsonObject = new JSONObject(json);
            info.versionCode = jsonObject.optInt("versionCode");
            info.url = jsonObject.optString("url");
            info.changelog = jsonObject.optString("changelog");
            info.md5 = jsonObject.optString("md5");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return info;
    }

    public static void updateApk(final BaseActivity context, String url) {
        HttpStringRequest request = new HttpStringRequest(Request.Method.GET, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                UpdateVersionInfo info = UpdateVersionInfo.parser(response);
                if (info.versionCode > context.application.getVersionCode()) {
                    Intent intent = new Intent(context, DialogUpdateActivity.class);
                    intent.putExtra("info", info);
                    context.startActivity(intent);
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });
        request.setTag(url);
        context.requestQueue.add(request);
    }
}
